package com.fd.dao.impl;

import com.fd.dao.CartDAO;
import com.fd.pojo.Cart;
import com.fd.pojo.Products;
import com.fd.util.Close;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class CartDAOImpl implements CartDAO {
    private Connection conn=null;
    private Statement st =null;
    private ResultSet rs=null;
    private PreparedStatement ps=null;
    private boolean execute=false;
    private List<Cart> cartList;
    private String sql;

    public boolean insertGoods(Products product) {
        try {
            conn = Close.getConn();
            sql="insert into cart (pid,pname,price) values (?,?,?)";
            ps = conn.prepareStatement(sql);
            ps.setInt(1,product.getPid());
            ps.setString(2,product.getPname());
            ps.setDouble(3,product.getPrice());
            int rs = ps.executeUpdate();
            if (rs>0){
                execute = true;
            }else{
                execute =false;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            Close.release(ps,conn);
        }
        return execute;
    }

    public List<Cart> queryAll() {

        try {
            conn=Close.getConn();
            st = conn.createStatement();
            sql = "select * from cart";
            rs = st.executeQuery(sql);
            cartList = new ArrayList<Cart>();
            while (rs.next()){
                Cart cart = new Cart();
                cart.setPid(rs.getInt("pid"));
                cart.setPname(rs.getString("pname"));
                cart.setPrice(rs.getDouble("price"));
                cartList.add(cart);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            Close.release(rs,st,conn);
        }
        return cartList;
    }

    public boolean reCartById(Integer pid) {
        try {
            conn = Close.getConn();
            sql = "delete from cart where pid=?";
            ps = conn.prepareStatement(sql);
            ps.setInt(1,pid);
            int i = ps.executeUpdate();
            if (i>0){
                execute=true;
            }else{
                execute=false;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return execute;
    }
}
